package com.jay.utils;

/**
 * @ClassName: HiStackTraceUtil
 * @Description: java类作用描述
 * @Author: yangjie
 * @Date: 2022/4/5 8:09 下午
 */
public class HiStackTraceUtil {

    public static StackTraceElement[] getCroppedRealStackTrack(StackTraceElement [] stackTrace,String ignorePackage,int mexDepth){
        return cropStackTrace(getRealStackTrack(stackTrace,ignorePackage),mexDepth);
    }
    /**
     * 获取除忽略包名之外的堆栈信息
     * @param stackTrace
     * @param ignorePackage
     * @return
     */
    private static StackTraceElement [] getRealStackTrack(StackTraceElement [] stackTrace,String ignorePackage){
        int ignoreDepth=0;
        int allDepth=stackTrace.length;
        String className;
        for(int i=allDepth-1;i>0;i--){
            className=stackTrace[i].getClassName();
            if(ignorePackage!=null&&className.startsWith(ignorePackage)){
                ignoreDepth=i+1;
                break;
            }
        }
        int realDepth=allDepth-ignoreDepth;
        StackTraceElement [] realStack=new StackTraceElement[realDepth];
        System.arraycopy(stackTrace,ignoreDepth,realStack,0,realDepth);
        return realStack;

    }
    /**
     * 裁减堆栈信息
     * @param callStack
     * @param maxDeptah
     * @return
     */
    private  static  StackTraceElement [] cropStackTrace(StackTraceElement [] callStack,int maxDeptah){
        int realDepth=callStack.length;
        if(maxDeptah>0){
            realDepth=Math.min(maxDeptah,realDepth);
        }
        StackTraceElement[] realStack=new StackTraceElement[realDepth];
        System.arraycopy(callStack,0,realStack,0,realDepth);
        return realStack;
    }
}
